var AdvancePaymentForm = function () {
  var PaymentFormModel = function (payment) {
    BaseModel.call(this);

    var self = this;
    var fn = {
      initData: function (payment) {
        if (payment === undefined) {
          self.type = '';
          self.source = '';
          self.sourceStr = '';
          self.advanceNo = '';
          self.paymentDay = null;
          self.receviePaymentUserName = '';
          self.relationBank = '';
          self.sumMoney = undefined;
        }
      }
    };

    this.clearInfo = function () {
      this.source = '';
      this.sourceStr = '';
      this.advanceNo = '';
      this.paymentDay = null;
      this.receviePaymentUserName = '';
      this.relationBank = '';
      this.sumMoney = undefined;
    };

    this.checkValid = function () {
      var fields = ['type', 'sumMoney', 'receviePaymentUserName', 'source', 'sourceStr', 'advanceNo', 'paymentDay', 'relationBank'];
      return this.checkRequiredFields(fields, true);
    };

    this.getObject = function (isAduit) {
      var postData = {};
      var fields = ['type', 'sumMoney', 'receviePaymentUserName', 'source', 'sourceStr', 'advanceNo', 'relationBank'];
      this.setPostData(postData, fields);

      var paymentDay = this.paymentDay;
      postData.paymentDay = moment(paymentDay).format('YYYY-MM-DD');

      if (isAduit) {
        postData.isAduit = true;
      }
      return postData;
    };

    fn.initData(payment);
  };

  var template = /* html */ `
    <div class="advance-payment-form" v-loading.fullscreen.lock="loading">
      <el-form label-width="100px" size="medium">
        <el-form-item label="收付款类型">
          <el-select v-model="paymentForm.type" class="form-input" @change="clearInfo">
            <el-option v-for="item in typeList" :key="item.value" :value="item.value" :label="item.label">
            </el-option>
          </el-select>
        </el-form-item>

        <template v-if="paymentForm.type!==''">
        <el-form-item :label="'预'+paymentTypeText+'金额'">
          <el-input-number is-decimal-zero v-model="paymentForm.sumMoney" class="form-input" :min="0" :precision="4" :controls="false">
          </el-input-number>
        </el-form-item>
        <el-form-item :label="'预'+paymentCustomerTypeText+'方'">
          <el-select filterable v-model="paymentForm.receviePaymentUserName" class="form-input">
            <template v-if="paymentForm.type===1">
              <el-option v-for="name in customerNameList" :key="name" :value="name"></el-option>
            </template>
            <template v-else>
              <el-option v-for="name in providerNameList" :key="name" :value="name"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item :label="paymentTypeText+'用途'">
          <el-select v-model="paymentForm.source" class="form-input">
            <el-option v-for="item in sourceList" :key="item.value" :value="item.value" :label="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="paymentTypeText+'用途描述'">
          <el-input v-model="paymentForm.sourceStr" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="合同编号">
          <el-input v-model="paymentForm.advanceNo" class="form-input"></el-input>
        </el-form-item>
        <el-form-item :label="'预'+paymentTypeText+'日期'">
          <el-date-picker v-model="paymentForm.paymentDay" class="form-input" value-format="timestamp" :editable="false"></el-date-picker>
        </el-form-item>
        <el-form-item label="银行卡号">
          <filter-select filterable v-model="paymentForm.relationBank" class="form-input" :options="bankCardList" value-field="num" label-field="num"
            :filter-method="cardFilterMehod">
            <template slot="item" slot-scope="scope">
              <div class="clearfix">
                <span>{{scope.option.num}}</span>
                <span style="float:right;color:#8492a6;margin-left:10px;font-size:12px">
                  {{scope.option.bankName}}
                </span>
              </div>
            </template>
          </filter-select>
        </el-form-item>
        </template>
      </el-form>

      <div style="text-align:center">
        <el-button size="medium" type="primary" @click="ensure(false)">提交</el-button>
        <el-button size="medium" type="primary" @click="ensure(true)">审核过账</el-button>
      </div>
    </div>
  `;

  return {
    props: {
      type: {
        type: String,
        default: 'add'
      },
      payment: {
        type: Object,
        default: function () {
          return null;
        }
      },
      dropdownOption: {
        type: Object,
        default: function () {
          return {};
        }
      }
    },

    computed: {
      paymentTypeText: function () {
        var type = this.paymentForm.type;
        return type === 1 ? '收款' : '付款';
      },
      paymentCustomerTypeText: function () {
        var type = this.paymentForm.type;
        return type === 1 ? '付款' : '收款';
      }
    },

    data: function () {
      var paymentForm;
      if (this.type === 'add') {
        paymentForm = new PaymentFormModel();
      }
      return {
        loading: false,
        paymentForm: paymentForm,
        typeList: i18n.getDropDown('warehouseBalance.detail.type', [1, 2]),
        sourceList: i18n.getDropDown('financeMgr.advancePayment.source', [1, 2, 3]),
        bankCardList: [],
        customerNameList: [],
        providerNameList: []
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.setBankCardList(),
        this.setCostNameList()
      ]).then(function () {
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      setBankCardList: function () {
        var dropdownOption = this.dropdownOption;
        var bankCardList = dropdownOption.bankCardList;
        if (bankCardList !== undefined) {
          this.bankCardList = bankCardList;
          return Promise.resolve(bankCardList);
        }

        var self = this;
        return ajaxRequest('finance/getAllBank').then(function (bankCardList) {
          bankCardList = _.map(bankCardList, function (card) {
            return {
              num: card.bankCardNumber,
              bankName: card.bank
            };
          });
          self.bankCardList = bankCardList;
          dropdownOption.bankCardList = bankCardList;
          return bankCardList;
        });
      },

      setCostNameList: function () {
        var dropdownOption = this.dropdownOption
        var customerNameList = dropdownOption.customerNameList;
        if (customerNameList !== undefined) {
          this.customerNameList = customerNameList;
          var providerNameList = dropdownOption.providerNameList;
          this.providerNameList = providerNameList;
          return Promise.resolve({
            customerNameList: customerNameList,
            providerNameList: providerNameList
          });
        }

        var self = this;
        return ajaxRequest('basicData/queryCustomersTow', {}, false).then(function (res) {
          var list = res.returnData;
          var customerNameList = [],
            providerNameList = [];
          for (var i = 0; i < list.length; i++) {
            var obj = list[i];
            var type = obj.type;
            if ([1, 3].indexOf(type) !== -1) {
              providerNameList.push(obj.customerName);
            }
            if ([2, 3].indexOf(type) !== -1) {
              customerNameList.push(obj.customerName);
            }
          }
          self.customerNameList = customerNameList;
          self.providerNameList = providerNameList;
          dropdownOption.customerNameList = customerNameList;
          dropdownOption.providerNameList = providerNameList;
          return {
            customerNameList: customerNameList,
            providerNameList: providerNameList
          };
        });
      },

      cardFilterMehod: function (query, option) {
        if (query === '') {
          return true;
        }
        query = query.toLowerCase();

        var num = option.num;
        num = num.toLowerCase();
        var bankName = option.bankName;
        bankName = bankName.toLowerCase();
        return num.indexOf(query) !== -1 || bankName.indexOf(query) !== -1;
      },

      clearInfo: function () {
        this.paymentForm.clearInfo();
      },

      ensure: function (isAduit) {
        var paymentForm = this.paymentForm;
        var code = paymentForm.checkValid();
        if (code !== '') {
          var type = paymentForm.type;
          var msgtype = type === 1 ? 'financeMgr.advancePayment.outBalance' : 'financeMgr.advancePayment.inBalance';
          var msg = i18n.getMsg(`${msgtype}.${code}`);
          this.$alert(msg, '信息');
          return;
        }

        var postData = paymentForm.getObject(isAduit);
        this.loading = true;
        var self = this;
        return ajaxRequest('finance/advancePayAdd',postData).then(function(){
          self.loading = false;
          self.$alert(`预${self.paymentTypeText}成功`,'信息',{
            callback:function(){
              self.$emit('payment-success');
            }
          });
        }).catch(function(){
          self.loading = false;
        });
      }
    },

    components: {
      FilterSelect: FilterSelect
    },

    template: template
  };
}();
